package cn.zhoutao.org.controller;

import cn.zhoutao.basic.anno.PreAuthorize;
import cn.zhoutao.basic.util.AjaxResult;
import cn.zhoutao.basic.util.LoginContext;
import cn.zhoutao.basic.util.PageList;
import cn.zhoutao.org.domain.Department;
import cn.zhoutao.org.query.DepartmentQuery;
import cn.zhoutao.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/dept")
public class DepartmentController {
    @Autowired
    private IDepartmentService departmentService;
    /**
     * 查询一条记录 GET
     */
    @GetMapping("/{id}")
    public Department queryById(@PathVariable("id") Long id){
         return  departmentService.queryById(id);
    }
    /**
     * 查询所有 GET
     */
    @GetMapping
    public  List<Department> queryAll(){
         return departmentService.queryAll();
    }
    /**
     * 新增和修改 put
     */
    @PutMapping
    public AjaxResult addOrUpdate (@RequestBody Department department){
        try {
        if (department.getId() == null){
            departmentService.save(department);
        }else {
            departmentService.update(department);
        }
        return AjaxResult.me();
    }catch (Exception e){
            e.printStackTrace();
            return AjaxResult
                    .me()
                    .setSuccess(false)
                    .setMessage("系统wa了，我们正在殴打程序员");
        }
    }
    /**
     * 删除一条记录 DELTTE
     */
    @DeleteMapping("/{id}")
    @PreAuthorize(name="删除一条部门数据",value = "dept:deleteById")
    public AjaxResult remove(@PathVariable("id") Long id){
        try {
            departmentService.removeById(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult
                    .me()
                    .setSuccess(false)
                    .setMessage("系统wa了，我们正在殴打程序员");
        }
        }
    /**
     * 高级查询 + 分页 Post
     */
    @PostMapping
    public PageList<Department> queryPage(@RequestBody DepartmentQuery query, HttpServletRequest request){
        System.out.println(LoginContext.getCurrentLogininfo(request));
        return departmentService.queryPage(query);
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @PatchMapping
    public AjaxResult batchRemove(@RequestBody List<Long> ids){
        try {
            departmentService.batchRemove(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult
                    .me()
                    .setSuccess(false)
                    .setMessage("系统wa了，我们正在殴打程序员");
        }
    }


    @GetMapping("/tree")
    public List<Department> queryTree(){
        return  departmentService.queryTree();
    }
}
